package com.untils;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Common {
	private static int index = 1;
	private static String path = "d:/xinxin/"; 
	
	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		Common common = new Common();
		String url = "http://760.s21i.faidns.com/872760/2/ABUIABACGAAghtW8lAUoyKiergMwmAI4gAI.jpg";
		int prefixEnd = url.lastIndexOf("!");
		int fileFormatBegin = url.lastIndexOf(".");
		prefixEnd = prefixEnd != -1 ? prefixEnd : fileFormatBegin;
		String fileFormat = url.substring(fileFormatBegin);
		url = url.substring(0, prefixEnd) + fileFormat;
		try {
			common.download(url, path + "sdg" + index + fileFormat);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param imageUrl
	 * @param path
	 * @throws IOException
	 */
	public static void download(String imageUrl, String path) throws IOException {
		byte[] buffer = new byte[4096];
		int len = 0;
		InputStream inputStream = getInputStream(imageUrl);
		DataInputStream input = new DataInputStream(inputStream);
//		FileOutputStream output = new FileOutputStream(new File(path));

		FileOutputStream output = new FileOutputStream(path);
         while (-1 != (len = inputStream.read(buffer))){
        	 output.write(buffer, 0, len);
         }
		input.close();
		output.close();
	}
	/**
	 * 
	 * @param imageUrl
	 * @return
	 * @throws IOException
	 */
	 public static InputStream getInputStream(String imageUrl) throws IOException{
	        InputStream inputStream = null;
	        HttpURLConnection httpURLConnection = null;

            URL url = new URL(imageUrl);
            if (null != url){
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod("GET");
                if (200 == httpURLConnection.getResponseCode()){
                    inputStream = httpURLConnection.getInputStream();
                }
            }
	        return inputStream;
	    }
	/**
	 * 
	 * @param keys
	 * @param result
	 * @return
	 */
	public static String replace(String[] keys, String result){
		for (String string : keys) {
			result = result.replaceAll(string, "");
		}
		return result;
	} 
}
